<template>
  <div class="dashboard-container">
    <el-container>
      <el-header>
        <h1>AgriTech 数据大屏</h1>
        <div class="weather">
          <i class="el-icon-sunny"></i>
          <span>晴 28°C</span>
        </div>
      </el-header>
      <el-main>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>大棚信息</span>
              </div>
              <div class="greenhouse-info">
                <p><strong>名称：</strong>{{greenhouseInfo.name}}</p>
                <p><strong>面积：</strong>{{greenhouseInfo.area}} 平方米</p>
                <p><strong>地址：</strong>{{greenhouseInfo.address}}</p>
                <p><strong>设备总数：</strong>{{deviceCount}}</p>
              </div>
            </el-card>
          </el-col>
          <el-col :span="16">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>实时数据</span>
              </div>
              <el-row :gutter="20">
                <el-col :span="12">
                  <h3>土壤检测数据</h3>
                  <ul class="soil-data">
                    <li v-for="(value, key) in soilData" :key="key">
                      <strong>{{key}}：</strong>{{value}}
                    </li>
                  </ul>
                  <el-button type="primary" size="small" @click="fetchSoilData">
                    获取数据
                  </el-button>
                </el-col>
                <el-col :span="12">
                  <h3>实时监控</h3>
                  <div class="camera-feed">
                    <EzvizCameraPreview
                        :url="cameraUrl"
                        :accessToken="accessToken"
                        :template="cameraTemplate"
                    />
                  </div>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>光照度时间曲线图</span>
              </div>
              <div id="soilTempHumidityChart" style="height: 300px;"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>空气温度柱状图</span>
              </div>
              <div id="npkChart" style="height: 300px;"></div>
            </el-card>
          </el-col>
        </el-row>
        <el-row style="margin-top: 20px;">
          <el-col :span="24">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>历史监控画面</span>
                <el-button type="primary" size="small" @click="captureCurrentImage">抓取当前画面</el-button> <!-- 新增按钮 -->
              </div>
              <el-timeline>
                <!-- 使用 v-for 动态渲染历史抓拍图片 -->
                <el-timeline-item
                    v-for="(activity, index) in activities"
                    :key="index"
                    :timestamp="activity.timestamp">
                  {{activity.content}}
                  <img :src="activity.image" style="width: 100px; height: 100px; object-fit: cover;">
                </el-timeline-item>
              </el-timeline>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import axios from 'axios';
import EzvizCameraPreview from '@/components/EzvizCameraPreview.vue';

export default {
  components: {
    EzvizCameraPreview
  },
  data() {
    return {
      greenhouseInfo: {
        name: '智能大棚A',
        area: 1000,
        address: '某某省某某市某某区'
      },
      deviceCount: 10,
      soilData: {
        '土壤PH值': '加载中...',
        '光照度': '加载中...',
        '二氧化碳': '加载中...',
        '空气温度': '加载中...',
        '空气相对湿度': '加载中...'
      },
      sensorData: {},
      activities: []  // 初始化为空数组，动态获取数据
    };
  },
  mounted() {
    this.fetchSensorData('light'); // 初始加载光照度数据
    this.fetchSensorData('temperature'); // 初始加载温度数据
    this.fetchActivities();  // 初始化时获取历史抓拍图片数据
    this.initCharts();
  },
  methods: {
    async captureCurrentImage() {
      try {
        // 从 localStorage 获取 userId
        const userId = localStorage.getItem('userId');  // 从本地存储中获取 u_id

        if (!userId) {
          this.$message.error('用户未登录，请先登录');
          return;
        }

        const deviceSerial = 'L29334649';  // 设备序列号

        // 发送 POST 请求到后端接口抓取当前监控画面
        const response = await axios.post('http://localhost:8080/camera/capture', null, {
          params: {
            userId,
            deviceSerial
          }
        });

        // 使用返回的 response 数据
        if (response.status === 200) {
          // 如果抓取成功，刷新历史活动
          this.fetchActivities();
          this.$message.success('当前画面已抓取并保存！');
        } else {
          // 如果失败
          this.$message.error('抓取当前画面失败，请重试');
        }
      } catch (error) {
        console.error('抓取当前画面失败:', error);
        this.$message.error('抓取当前画面失败，请重试');
      }
    },


    async fetchActivities() {
      try {
        const response = await axios.get('http://localhost:8080/camera/images');  // 获取后端的图片活动数据
        this.activities = response.data.map(item => ({
          timestamp: item.imageTime,
          image: `http://localhost:8080/${item.imageUrl.replace(/\\/g, '/')}`  // 修正路径，确保前端可以访问
        }));
      } catch (error) {
        console.error('获取历史活动失败:', error);
        this.$message.error('获取历史活动失败，请重试');
      }
    },

    async fetchSensorData(sensorType) {
      try {
        const response = await axios.get(`http://localhost:8080/sensor/data?sensor=${sensorType}`);
        const data = response.data;

        // 更新 sensorData
        this.sensorData[sensorType] = data[sensorType];

        // 将获取的数据传递到图表更新方法
        if (sensorType === 'light') {
          this.updateLightChart(data[sensorType]);  // 传递光照度数据
        } else if (sensorType === 'temperature') {
          this.updateTemperatureChart(data[sensorType]);  // 传递温度数据
        }

      } catch (error) {
        console.error(`获取 ${sensorType} 数据失败:`, error);
        this.$message.error(`获取 ${sensorType} 数据失败，请重试`);
      }
    },

    // 更新光照度图表
    updateLightChart(lightData) {
      const timestamps = lightData.map(item => item.updateTime);  // 使用正确的字段名
      const lightValues = lightData.map(item => item.sensorPrice);  // 使用正确的字段名

      const chart = echarts.init(document.getElementById('soilTempHumidityChart'));
      const option = {
        title: {
          text: '光照度变化'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['光照度']
        },
        xAxis: {
          type: 'category',
          data: timestamps
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '光照度',
            type: 'line',
            data: lightValues
          }
        ]
      };
      chart.setOption(option);
    },

    // 更新温度图表
    updateTemperatureChart(temperatureData) {
      const timestamps = temperatureData.map(item => item.updateTime);  // 使用正确的字段名
      const temperatureValues = temperatureData.map(item => item.sensorPrice);  // 使用正确的字段名

      const chart = echarts.init(document.getElementById('npkChart'));
      const option = {
        title: {
          text: '温度变化'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['温度']
        },
        xAxis: {
          type: 'category',
          data: timestamps
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '温度',
            type: 'bar',
            data: temperatureValues
          }
        ]
      };
      chart.setOption(option);
    },

    async fetchSoilData() {
      try {
        const response = await axios.post('http://localhost:8080/sensor/fetchData',
            new URLSearchParams({
              boxNo: '300822040454',  // 固定编号
            }), {
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
              }
            });

        const successResponse = response.data;  // 获取后端返回的成功响应

        if (successResponse && successResponse.data) {
          const rawData = successResponse.data;

          // 如果数据格式是文本而非 JSON，则尝试手动解析
          if (typeof rawData === 'string') {
            // 将传感器数据字符串转换为 JSON 数组
            const parsedData = rawData.split("\n").map(line => {
              const match = line.match(/Sensor ID: (\d+), Name: (.*), Value: ([\d.]+), Timestamp: (.*)/);
              if (match) {
                return {
                  id: match[1],
                  name: match[2],
                  value: parseFloat(match[3]),
                  timestamp: match[4]
                };
              }
              return null;
            }).filter(item => item !== null);

            // 处理传感器数据并更新视图
            const dataMap = {};
            parsedData.forEach(item => {
              dataMap[item.name] = item.value;
            });

            this.soilData = {
              '土壤PH值': `${dataMap['土壤PH值'] || 'N/A'}`,
              '光照度': `${dataMap['光照度'] || 'N/A'} lux`,
              '二氧化碳': `${dataMap['二氧化碳'] || 'N/A'} ppm`,
              '空气温度': `${dataMap['空气温度'] || 'N/A'}°C`,
              '空气相对湿度': `${dataMap['空气相对湿度'] || 'N/A'}%`
            };
          } else {
            console.error('Invalid data format');
            this.$message.error('获取土壤数据失败，请重试');
          }
        } else {
          console.error('No data found in response');
          this.$message.error('获取土壤数据失败，请重试');
        }
      } catch (error) {
        console.error('获取土壤数据失败:', error);
        this.$message.error('获取土壤数据失败，请重试');
      }
    }
  }
};
</script>



<style scoped>
.dashboard-container {
  height: 100vh;
  background-color: #f0f2f5;
}
.el-header {
  background-color: #409EFF;
  color: white;
  line-height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.weather {
  font-size: 18px;
}
.el-main {
  padding: 20px;
}
.box-card {
  margin-bottom: 20px;
}
.greenhouse-info p {
  margin: 5px 0;
}
.soil-data {
  list-style-type: none;
  padding: 0;
}
.soil-data li {
  margin-bottom: 5px;
}
.camera-feed {
  text-align: center;
}
.camera-feed img {
  max-width: 100%;
  height: auto;
}
</style>


